package com.yunkaweilai.android.activity.operation.Message;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.base.BaseActivity;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.interfaces.MyDialogInterface;
import com.yunkaweilai.android.model.CountMainBean;
import com.yunkaweilai.android.model.GroupMessageBean;
import com.yunkaweilai.android.model.GroupMessageSendLoadingBean;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.InputMethodUtils;
import com.yunkaweilai.android.utils.TitleBuilder;
import com.yunkaweilai.android.utils.Utils;
import com.yunkaweilai.android.view.dialog.MyDialog;
import com.yunkaweilai.android.view.dialog.shop.ShopCodeSingleDialog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.addapp.pickers.listeners.OnItemPickListener;
import cn.addapp.pickers.listeners.OnSingleWheelListener;
import cn.addapp.pickers.picker.SinglePicker;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;

/**
 * 短信群发
 */

public class GroupMessage extends BaseActivity implements BGARefreshLayout.BGARefreshLayoutDelegate, MyDialogInterface {

    @BindView(R.id.message_group_et1)
    EditText mEditText1;
    @BindView(R.id.id_group_message_t1)
    TextView mTextViewTem;
    @BindView(R.id.id_group_message_img1)
    ImageView mImageView1;
    @BindView(R.id.id_group_message_t2)
    TextView mTextViewMem;
    @BindView(R.id.id_group_message_img2)
    ImageView mImageView2;
    @BindView(R.id.group_message_btn_right)
    Button mButtonRight;
    @BindView(R.id.id_group_message_t4)
    TextView mTextViewNum;
    @BindView(R.id.group_message_number)
    TextView mTextViewSMSnum;

    private GroupMessageBean mGroupMessageBean;
    private List<String> mListModel = new ArrayList<>();
    private String ChoosedModelId = "0";//当前选择模式id 自行编辑 = -99 ， 其他模板即为id 自行编辑传值写死了
    private String IdList = "";
    private int IdListNum = 0;
    private int pageForLoading = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_message);
        ButterKnife.bind(this);
        new TitleBuilder(mAc).setLeftImage(R.mipmap.ic_go_back).setLeftOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                InputMethodUtils.closeSoftKeyboard(mAc);
                finish();
            }
        }).setTitleText("短信群发");
        initModel();
        initSMSnum();
        initclick();

    }

    //设置控件的点击事件
    private void initclick() {
        mTextViewTem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pickerSelSex(mListModel);
            }
        });
        mImageView1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pickerSelSex(mListModel);
            }
        });
        mTextViewMem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mAc.startActivityForResult(new Intent(mAc, CommonGroupMemberActivity.class), 101);
            }
        });
        mImageView2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mAc.startActivityForResult(new Intent(mAc, CommonGroupMemberActivity.class), 101);
            }
        });
        mButtonRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setRight();
            }
        });
        mEditText1.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                setSMStext();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    //设置估算数量，要发多少条短信
    private void setSMStext() {
        int x = mEditText1.getText().toString().length();
        int num = 0;
        while (x > 0) {
            num++;
            x = x - 68;//一条短信字数限制为68
        }
        mTextViewNum.setText("2.当前字数大约" + mEditText1.getText().toString().length() + "字，约扣" + IdListNum * num + "条短信（仅供参考，实际因替换/添加参数字数不定，以短信历史记录为准）");

    }

    //确定事件
    private void setRight() {
        if (mTextViewMem.getText().toString().equals("0人") || IdList.isEmpty()) {
            showToast("还未选择发送人");
            return;
        }
        if (ChoosedModelId.equals("0") && mEditText1.getText().toString().isEmpty()) {
            showToast("尚未输入短信内容");
            return;
        }
        MyDialog myDialog = new MyDialog(mAc, this, "提示", "确定发送短信吗？");
        myDialog.show();

    }

    //发送短信 第一个自定义，第二个非自定义，要改啥两个一起改
    private void inithttp() {
        pageForLoading = 1;
        if (ChoosedModelId.equals("0")) {
            HttpRequest.postUrl(Api.APP_SMS_SEND)
                    .addParams("StrMemberId", IdList)//列表会员id
                    .addParams("smsDIYTemplateId", "-99")//模板id -99代表自行编辑
                    .addParams("sms_content", mEditText1.getText().toString())
                    .execute(new PostProcess.StringCallBack() {
                        @Override
                        public void onResponse(String json) {
                            boolean checkCode = Utils.checkCode(mAc, json);
                            if (checkCode) {

                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        inithttpLoading(pageForLoading, 0);
                                    }
                                }, 2000);
                            } else {
                                dismissProgressDialog();
                            }
                        }

                        @Override
                        public void onError(Exception e) {
                            dismissProgressDialog();
                            showToast(e.getMessage());
                        }
                    });
        } else {
            HttpRequest.postUrl(Api.APP_SMS_SEND)
                    .addParams("StrMemberId", IdList)//列表会员id
                    .addParams("smsDIYTemplateId", ChoosedModelId)//模板id
                    .execute(new PostProcess.StringCallBack() {
                        @Override
                        public void onResponse(String json) {
                            boolean checkCode = Utils.checkCode(mAc, json);
                            if (checkCode) {
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        inithttpLoading(pageForLoading, 0);
                                    }
                                }, 2000);
                            } else {
                                dismissProgressDialog();
                            }
                        }

                        @Override
                        public void onError(Exception e) {
                            dismissProgressDialog();
                            showToast(e.getMessage());
                        }
                    });
        }
    }

    //短信发送过程加载
    private void inithttpLoading(int page, int sucessNum) {
        HttpRequest.postUrl(Api.APP_SMS_SEND_LOADING)
                .addParams("page", page + "")
                .addParams("sucessNum", sucessNum + "")
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
//                            dismissProgressDialog();
                            Gson gson = new Gson();
                            GroupMessageSendLoadingBean messageSendLoadingBean = gson.fromJson(json, GroupMessageSendLoadingBean.class);
                            setmProgress("正在发送中第" + pageForLoading + "条");
                            pageForLoading = messageSendLoadingBean.getData().getPage();
                            if (messageSendLoadingBean.getData().isNext()) {
                                inithttpLoading(pageForLoading, messageSendLoadingBean.getData().getSucessNum());
                            } else if (!messageSendLoadingBean.getData().isNext()) {
                                dismissProgressDialog();
                                ShopCodeSingleDialog myDialog = new ShopCodeSingleDialog(mAc, messageSendLoadingBean.getData().getSuccessMsg());
                                myDialog.show();
//                                initSMSnum();
                                mTextViewSMSnum.setText("本店剩余短信数：" + messageSendLoadingBean.getData().getSmsNum());
                                IdList = "";
                                mTextViewMem.setText("0人");
                                mTextViewTem.setText("自行编辑");
                                ChoosedModelId = "0";
                                mEditText1.setText("");

                            }
                        } else {
                            dismissProgressDialog();
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        dismissProgressDialog();
                        showToast(e.getMessage());
                    }
                });

    }

    //获取短信剩余数
    private void initSMSnum() {
        mTextViewSMSnum.setText("本店剩余短信数：---");
        HttpRequest.postUrl(Api.COUNT_HOME)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            Gson gson = new Gson();
                            CountMainBean countBean = gson.fromJson(json, CountMainBean.class);
                            mTextViewSMSnum.setText("本店剩余短信数：" + countBean.getData().getInfo().getSms_count());

                        } else {
                            showToast("服务器发生错误");
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        showToast("服务器发生错误");
                    }
                });
    }

    //获取模板
    private void initModel() {
        HttpRequest.postUrl(Api.APP_DIY_TEM)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        Gson gson = new Gson();
                        mGroupMessageBean = gson.fromJson(json, GroupMessageBean.class);
                        mListModel.add("自行编辑");
                        for (int i = 0; i < mGroupMessageBean.getData().getList().size(); i++) {
                            mListModel.add(mGroupMessageBean.getData().getList().get(i).getSms_title());
                        }
                    }

                    @Override
                    public void onError(Exception e) {

                    }
                });
    }

    //模板选择
    private void pickerSelSex(List<String> list) {
        SinglePicker<String> picker = new SinglePicker<>(this, list);
        picker.setCanLoop(false);//不禁用循环
        picker.setLineVisible(true);
        picker.setShadowVisible(true);
        picker.setTextSize(18);
        picker.setSelectedIndex(0);
        picker.setWheelModeEnable(true);
        //启用权重 setWeightWidth 才起作用
        picker.setWeightEnable(true);
        picker.setWeightWidth(1);
        picker.setSelectedTextColor(0xFF279BAA);//前四位值是透明度
        picker.setUnSelectedTextColor(0xFF999999);
        picker.setOnSingleWheelListener(new OnSingleWheelListener() {
            @Override
            public void onWheeled(int index, String item) {

            }
        });
        picker.setOnItemPickListener(new OnItemPickListener<String>() {
            @Override
            public void onItemPicked(int index, String item) {
                mTextViewTem.setText(item);
                if (index == 0) {
                    mEditText1.setText("");
                    ChoosedModelId = "0";
                    editTextEnable(true, mEditText1);
                } else {
                    mEditText1.setText(mGroupMessageBean.getData().getList().get(index - 1).getSms_content());
                    ChoosedModelId = mGroupMessageBean.getData().getList().get(index - 1).getId();//index-1是因为在列表第一个加了个自行编辑
                    editTextEnable(false, mEditText1);
                }
            }
        });
        picker.show();
    }

    private void editTextEnable(boolean enable, EditText editText) {
        editText.setFocusable(enable);
        editText.setFocusableInTouchMode(enable);
        editText.setLongClickable(enable);
        editText.setHorizontallyScrolling(false);
//        editText.setInputType(enable ? InputType.TYPE_TEXT_FLAG_MULTI_LINE : InputType.TYPE_NULL);
    }

    //从别的地方返回的值
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            switch (requestCode) {
                case 101://从选择人返回
                    IdList = data.getStringExtra("IdList");
                    String s = data.getStringExtra("IdListNum");
                    IdListNum = Integer.parseInt(s);
                    mTextViewMem.setText(IdListNum + "人");
                    setSMStext();
                    break;
            }
        }
    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        initSMSnum();
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        return false;
    }

    //弹窗点击事件
    @Override
    public void RightClick() {
        showProgressDialog("请勿关闭页面，短信发送中...");
        inithttp();
    }

    @Override
    public void CancelClick() {

    }
}
